//
//  MyPie.m
//  QiuDouMaDai
//
//  Created by 王威 on 2016/12/21.
//  Copyright © 2016年 王威. All rights reserved.
//

#import "MyPie.h"
@implementation MyPie{
    CGFloat percentage;
}
-(id)initWithFrame:(CGRect)frame{
    self=[super initWithFrame:frame];
    if (self) {
        self.sliceLayerArray=[[NSMutableArray alloc]init];
        self.textArray=[[NSMutableArray alloc]init];
//        self.colorArray=[[NSMutableArray alloc]init];
//        self.textColorr=[[NSMutableArray alloc]init];
    }
    return self;
}
-(void)setDataArray:(NSArray *)dataArray{
    _dataArray=dataArray;
    CGFloat startAngle=0;
    CGFloat endAngle=0;
    for (int i=0; i<dataArray.count; i++) {
        percentage=[dataArray[i] floatValue];
        CGFloat angle=percentage*M_PI*2;
        endAngle=angle+startAngle;
        WWShapeLayer *shaperLayer=[WWShapeLayer layer];
        shaperLayer.startAngle=startAngle;
        shaperLayer.endAngle=endAngle;
        shaperLayer.radius=100.0f;
        shaperLayer.centerPoint=CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
        shaperLayer.tag=i;
        shaperLayer.fullColor=[UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
//        shaperLayer.fullColor=(__bridge UIColor *)([_colorArray[i] color]);
        [shaperLayer creat];
        [self.layer addSublayer:shaperLayer];
        [self.sliceLayerArray addObject:shaperLayer];
        CATextLayer *textLayer=[CATextLayer layer];
        textLayer.frame=CGRectMake(shaperLayer.centerPoint.x + cosf((startAngle + endAngle) / 2) * 50 - 15, shaperLayer.centerPoint.y + sinf((startAngle + endAngle) / 2) * 50 - 10, 40, 20);
        textLayer.string = [NSString stringWithFormat:@"%1.f%%", percentage * 100];
        shaperLayer.text=_textArray[i];
        textLayer.fontSize=14.0f;
        textLayer.contentsScale=2;
//        textLayer.foregroundColor=[UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1].CGColor;
        textLayer.foregroundColor=[UIColor whiteColor].CGColor;
//        textLayer.foregroundColor=[_textColorr[i] color];
        [shaperLayer addSublayer:textLayer];
        startAngle =endAngle;
    }
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    CGPoint touchPoint = [[touches anyObject] locationInView:self];
    for (WWShapeLayer *shapeLayer in _sliceLayerArray) {
        //判断选择区域
        if (CGPathContainsPoint(shapeLayer.path, 0, touchPoint, YES)) {
            shapeLayer.seclected = YES;
            [self.delegate touchTheShapeLayer:shapeLayer];
        } else {
            shapeLayer.seclected = NO;
        }
    }
}
@end
